In this reading, you'll learn what key arguments are required to establish a connection between MySQL and Python. And you'll learn how to handle connection failures with try/catch.

Connecting Python with a MySQL database.

Python communicates with MySQL using the mysql-connector. This is an external library that acts as a driver. It converts Python string objects into viable SQL statements that can be executed on MySQL.

The results of these SQL statements are then parsed and returned to the Python client in a manner that is compatible with Python datatypes and structures.

To connect with a MySQL backend database, a Python client program must furnish the appropriate connection parameters.

These parameters typically include specifying the following information:

The following screenshot displays the code for a typical connection with a MySQL database using a Python MySQL connector class:

Let’s explore this code in more detail.

Import connector

The first line imports mysql.connector as an alias called connector . This code imports the functionality of the connector into the Python environment.

Parameters

The second line demonstrates how the connect function in the connector accepts a variety of parameters.

Typically, when connecting to the database, a username and password must be passed as parameters to gain access to the MySQL database.

There are also several optional parameters that can also be furnished. Let’s take a closer look at these parameters.

Port number

One example of these parameters is the port number. This typically defaults to 3306 for a MySQL database, but it can be configured to another port.

A port is a way of gaining access to a computer. It’s a method of separating various channels of communication in and out of your system so that different applications can execute their respective code.

The reason for using different ports is so that applications can receive an instantaneous response when the appropriate connection is made with a system.

If there was just one port, then there would be a bottleneck of requests to a system. This would make it impossible to facilitate an application getting an immediate response when a request is made if another application is using that port.

Local host

For all the examples in this course the local host is used to host the database. Essential communication is made within the laptop itself.

However, in larger organizations this default setting will more than likely be configured to some external hosting site.

In the example provided, the sample name domain.com is used to signify that you are making an external call. You can furnish this setting with a domain name or IP address.

Database name

Finally, you can also pass the given database name as a parameter. This points the connection object directly at the required database. In the example provided, the connection object is pointed to the little_lemon database.

However, there can be many different databases, so the database name can be changed as required.

Alternatively, you can also use the cursor object of the connection class to directly access a database, using the following code:

cursor.execute("USE database_name")

Connection issues

There are many potential issues that can arise when connecting to a database. Not allowing for these issues can cause your application to crash unexpectedly in a production environment.

To avoid these issues, it’s a good idea to use Python’s try/except error handling, as in the following example:

Try/except is a built-in Python error handling code block. It first executes the statement and provides the compiler with two possibilities to explore, instead of just one that might crash the program.

In the above example, the incorrect username causes the try block to fail. So instead, the except block is run.

Mysql-connector has a library called errorcode specifically designed for handling these exceptions.

The following code example modifies the code of the above example so that the programmer can receive an accurate message as to what issue might be throwing the error.

The initial connection attempt can be found in the try section. The except contains a series of if/else conditional statements that allow for different connection issues one might have. These might relate to connection, credential or any range of syntax issues.

First the username and password are checked. Then Python checks if the target database exists. Finally, an open-ended error message is displayed which prints a reference to any issue not explicitly outlined in the code.

Conclusion

This reading exemplifies how you can combine Python’s built in try/except block with mysql-connector's error handling module to write more elegant code.

The focus of this reading was placed on checking the username, password and database. MySQL supports several additional ones such as data error, database error and integrity error.

To learn more about useful error codes and how to use them consult the additional resources for more information.